package com.freejava.testRocket;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 异步方式的生产者
 */
public class AsyncProducer {

    public static void main(String[] args) throws Exception {
        // 创建一个消息队列生产者，并设置一个独一无二的group名称
        DefaultMQProducer producer = new DefaultMQProducer("unique_group_name_for_this");
        // 设置name server的地址
        producer.setNamesrvAddr("localhost:9876");
        // 启动这个实例
        producer.start();
        producer.setRetryTimesWhenSendAsyncFailed(0);

        int count = 100;

        final CountDownLatch countDownLatch = new CountDownLatch(count);

        for (int i = 0; i < count; i++) {
            try {
                final int index = i;
                Message msg = new Message("test_topic_1212", "TagTwo", "Order12343", "Hi all".getBytes(RemotingHelper.DEFAULT_CHARSET));
                producer.send(msg, new SendCallback() {
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        countDownLatch.countDown();

                        System.out.println(index + " OK " + sendResult.getMsgId());
                    }

                    @Override
                    public void onException(Throwable e) {
                        countDownLatch.countDown();
                        System.out.printf("%-10d Exception %s %n", index, e);
                        e.printStackTrace();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 间隔3秒
        countDownLatch.await(3, TimeUnit.SECONDS);
        producer.shutdown();

    }
}
